package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.feignclient.client.ArticleFeign;
import com.heima.feignclient.client.WemediaFeign;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.ApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.ApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.validation.constraints.NotNull;
import java.lang.invoke.LambdaMetafactory;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-09-15
 */
@Slf4j
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {

    @Override
    public PageResult<UserAuthDto> findByPage(AuthDto dto) {
//        设置分页条件
        IPage<ApUserAuth> iPage = new Page<>(dto.getPage(),dto.getSize());
//        设置查询条件
        LambdaQueryWrapper<ApUserAuth> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(dto.getStatus() != null,ApUserAuth::getStatus,dto.getStatus());
//        分页查询
        IPage<ApUserAuth> userAuthIPage = page(iPage, queryWrapper);
        if(CollectionUtils.isEmpty(userAuthIPage.getRecords())){
            log.info("没有查询到数据");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        构造返回对象
        return new PageResult<>(dto.getPage(),
                dto.getSize(),
                userAuthIPage.getTotal(),
                BeanHelper.copyWithCollection(userAuthIPage.getRecords(),UserAuthDto.class));
    }

    @Autowired
    private ApUserService apUserService;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void userAuth(AuthDto dto, int status) {
//        获取认证信息id
        Integer authId = dto.getId();
//        根据id 修改认证状态，原因
        ApUserAuth userAuth = new ApUserAuth();
        userAuth.setId(authId);
        userAuth.setStatus(status);
        userAuth.setReason(status==9?"":dto.getMsg());
        boolean b = updateById(userAuth);
        if(!b){
            log.error("修改用户审核状态失败，authId={}",authId);
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        如果不通过，直接结束
        if(status==2){
            log.info("用户认证不通过，直接结束，authId={}",authId);
            return ;
        }
//        根据认证信息id，查询认证信息，获取ap_user_id
        userAuth = getById(authId);
        Integer userId = userAuth.getUserId();
//        根据ap_user_id 查询ap_user 的数据
        ApUser apUser = apUserService.getById(userId);
//        远程调用，自媒体服务，创建自媒体用户
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setApUserId(userId);
        wmUserDto.setName(apUser.getName());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setStatus(9);
        wmUserDto.setPhone(apUser.getPhone());
        wmUserDto.setImage(apUser.getImage());
        try {
            Integer wmUserId = wemediaFeign.userSave(wmUserDto);
            wmUserDto.setId(wmUserId);
        }catch (Exception e){
            log.error("远程调用wemedia，创建用户失败,userId={}",userId);
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        远程调用，article服务，创建作者
        AuthorDto authorDto = new AuthorDto();
        authorDto.setUserId(userId);
        authorDto.setWmUserId(wmUserDto.getId());
        authorDto.setName(apUser.getName());
        authorDto.setType(2);
        try {
            Integer authorId = articleFeign.saveAuthor(authorDto);
        }catch (Exception e){
            log.error("远程调用article，创建用户失败,userId={}",userId);
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
//        修改user的flag状态，改为 1- 自媒体人
        apUser = new ApUser();
        apUser.setId(userId);
        apUser.setFlag(1);
        boolean b1 = apUserService.updateById(apUser);
        if(!b1){
            log.error("修改用户flag失败,userId={}",userId);
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
